package com.aos.erp.schools.rest.sys;

import com.aos.erp.common.bean.ResultEntity;
import com.aos.erp.common.constant.GlobalConstant;
import com.aos.erp.common.exception.BizException;
import com.aos.erp.schools.model.sys.User;
import com.aos.erp.schools.model.sys.dto.UserDto;
import com.aos.erp.schools.model.sys.vo.UserVo;
import com.aos.erp.schools.service.sys.UserService;
import com.aos.erp.schools.util.UserUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * @program: erp
 * @description: 后台用户
 * @author: tanzhiyu
 * @create: 2018-10-31 11:27
 **/
@Api(value = "后台用户", tags = {"后台用户API"})
@RestController("RESTUserController")
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    GlobalConstant globalConstant;

    /**
     * 新增用户
     *
     * @param userVo
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "新增用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户账号", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "name", value = "用户姓名", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "depCode", value = "部门组织code", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "positionId", value = "岗位id", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "expireDatetime", value = "用户到期时间", required = false, dataType = "String", paramType = "Query")
    })
    @PostMapping(value = "/addUser")
    public ResultEntity addUser(UserVo userVo, String currentUserId) throws Exception {
        if (StringUtils.isEmpty(currentUserId)) {
            throw new BizException("请重新登录");
        }
        if (StringUtils.isBlank(userVo.getUsername())) {
            return ResultEntity.failed("用户账号不能为空", ResultEntity.CODE_NULL);
        }
        if (StringUtils.isBlank(userVo.getDepCode().toString())) {
            return ResultEntity.failed("部门组织code不能为空", ResultEntity.CODE_NULL);
        }
        if (StringUtils.isBlank(userVo.getPositionId().toString())) {
            return ResultEntity.failed("岗位id不能为空", ResultEntity.CODE_NULL);
        }
        //TODO
        Long operatorId = Long.valueOf(currentUserId);//操作人
        userVo.setOperatorId(operatorId);
        Map<String, Object> map = userService.addBean(userVo, globalConstant.getAPP_CODE_SCHOOL());
        return ResultEntity.success(map, "保存成功");
    }

    @ApiOperation(value = "修改用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "name", value = "用户姓名", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "depCode", value = "部门组织code", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "positionId", value = "岗位id", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "expireDatetime", value = "用户到期时间", required = false, dataType = "String", paramType = "Query")
    })
    @PostMapping("/updateUser")
    public ResultEntity updateUser(UserVo userVo, String currentUserId, String userId) throws Exception {
        if (StringUtils.isEmpty(currentUserId)) {
            throw new BizException("请重新登录");
        }
        if (StringUtils.isBlank(userVo.getId().toString())) {
            return ResultEntity.failed("用户ID不能为空", ResultEntity.CODE_NULL);
        }
        if (StringUtils.isBlank(userVo.getDepCode().toString())) {
            return ResultEntity.failed("部门组织code不能为空", ResultEntity.CODE_NULL);
        }
        if (StringUtils.isBlank(userVo.getPositionId().toString())) {
            return ResultEntity.failed("岗位id不能为空", ResultEntity.CODE_NULL);
        }
        //TODO
        Long operatorId = Long.valueOf(currentUserId);
        userVo.setOperatorId(operatorId);
        int i = userService.updateObject(userVo);
        if (i > 0) {
            return ResultEntity.success("修改成功");
        } else {
            return ResultEntity.success("修改失败");
        }
    }

    @ApiOperation(value = "删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "String", paramType = "Query")
    })
    @PostMapping("/delUser")
    public ResultEntity delUser(String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            return ResultEntity.failed("用户ID不能为空", ResultEntity.CODE_NULL);
        }
        int i = userService.isDel(id, globalConstant.getAPP_CODE_SCHOOL());
        if (i > 0) {
            return ResultEntity.success("删除成功");
        } else {
            return ResultEntity.success("删除失败");
        }
    }


    @ApiOperation(value = "分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "当前页码", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = " 每页显示条数", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "用户姓名", required = false, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "username", value = "用户账号", required = false, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "depName", value = "部门名称", required = false, dataType = "String", paramType = "Query")
    })
    @PostMapping("/list")
    public ResultEntity<IPage<UserDto>> queryPageBean(@RequestParam(name = "pageIndex", defaultValue = "1") Integer pageIndex,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      @RequestParam(name = "name", required = false) String name,
                                                      @RequestParam(name = "username", required = false) String username,
                                                      @RequestParam(name = "depName", required = false) String depName,
                                                      @RequestParam(name = "currentUserId", required = true) String currentUserId) throws Exception {
        //TODO 部门组织code
        String depCode = UserUtil.getUserDepCode(currentUserId);
        if (StringUtils.isBlank(depCode)) {
            return ResultEntity.failed("部门组织code不能为空", ResultEntity.CODE_NULL);
        }
        return ResultEntity.success(userService.queryByPage(pageIndex, pageSize, depCode, name, username, depName));
    }

    /**
     * 根据用户名查询
     *
     * @param name
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据用户名查询")
    @PostMapping("/getUser")
    public ResultEntity getUser(String name) throws Exception {
        if (StringUtils.isBlank(name)) {
            return ResultEntity.failed("账号或密码不能为空", ResultEntity.CODE_NULL);
        }
        User user = userService.findByName(name);
        return ResultEntity.success(user);
    }

    @ApiOperation(value = "根据用户id查询")
    @PostMapping("/getUserId")
    public ResultEntity getUserId(String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            return ResultEntity.failed("用户id不能为空", ResultEntity.CODE_NULL);
        }
        UserDto userDto = userService.findById(Long.valueOf(id));
        return ResultEntity.success(userDto, "获取用户信息");
    }

    /**
     * 系统登录
     *
     * @param username 账号
     * @param password 密码
     * @return
     */
    @ApiOperation(value = "系统登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "账号", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "Query")
    })
    @PostMapping("/login")
    public ResultEntity login(HttpServletRequest request, HttpServletResponse response, @CookieValue(value = "captchaCode", required = false) String captchaCode, String username, String password, String code) throws BizException {
        //TODO
        /* if (Objects.isNull(captchaCode)){
            return ResultEntity.failed("cookie为空");
        }*/
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ResultEntity.failed("账号或密码不能为空", ResultEntity.CODE_NULL);
        }
        if (Objects.isNull(code)) {
            return ResultEntity.failed("验证码不能为空");
        }

        Map<String, Object> mapUser = userService.login(request, response, username, password, code, captchaCode, globalConstant.getAPP_CODE_SCHOOL());
        return ResultEntity.success(mapUser, "登录成功");
    }

    @ApiOperation(value = "退出登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", required = true, dataType = "String", paramType = "Query")
    })
    @PostMapping("/logout")
    public ResultEntity logout(String token) throws BizException {
        //TODO
        if (Objects.isNull(token)) {
            return ResultEntity.failed("用户token不能为空");
        }
        userService.logout(token);
        return ResultEntity.success("退出成功");
    }

    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户账号", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "password", value = "用户新密码", required = true, dataType = "String", paramType = "Query"),
            @ApiImplicitParam(name = "oldpassword", value = "用户旧密码", required = true, dataType = "String", paramType = "Query")
    })
    @PostMapping("/changePassword")
    public ResultEntity changePassword(HttpServletRequest request, HttpServletResponse response, String username,
                                       String password, String oldpassword, @RequestParam(name = "currentUserId", required = true) String currentUserId) throws Exception {
        if (StringUtils.isBlank(username)) {
            return ResultEntity.failed("账号不能为空", ResultEntity.CODE_NULL);
        }
        if (StringUtils.isBlank(password)) {
            return ResultEntity.failed("用户新密码不能为空", ResultEntity.CODE_NULL);
        }
        if (StringUtils.isBlank(oldpassword)) {
            return ResultEntity.failed("用户旧密码不能为空", ResultEntity.CODE_NULL);
        }
        int i = userService.changePassword(username, password, oldpassword, currentUserId,globalConstant.getAPP_CODE_SCHOOL());
        return i > 0 ? ResultEntity.success() : ResultEntity.failed();
    }

}
